package unit04.day05;
/**
 * 多线程并发访问同一资源时，就会形成抢的现象。由于线程切换时机不确定，可能导致执行代码顺序混乱
 * 严重时会导致系统瘫痪
 * @author Administrator
 *
 */
public class SyncDemo1 {

	public static void main(String[] args) {
		final Table table = new Table();
		Thread t1 = new Thread() {
			public void run() {
				Thread.yield();
				while(true) {
					System.out.println(getName()+ ":" + table.getBeans());
				}
			}
		};
		Thread t2 = new Thread() {
			public void run() 
			{
				Thread.yield();
				while(true) {
					System.out.println(getName()+ ":" + table.getBeans());
				}
				
			}
		};
		t1.start();
		t2.start();
	}

}


class Table{
	private int beans = 20;
	//synchronized同步方法，即多个线程不能同时进入方法内部执行
	public synchronized int getBeans() {
		if(beans == 0) {
			throw new RuntimeException("没有豆子了");
		}
		Thread.yield();
		return beans--;
	}
}